package com.itfreer.gis.data.fileanalyze;

import com.itfreer.gis.data.file.ShapeFileDataEditServer;
import com.itfreer.utils.json.JsonUtils;
import com.itfreer.utils.zip.ZipperUtils;
import org.opengis.feature.simple.SimpleFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FilenameFilter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * shape文件解析服务
 */
@Component("shapeFileAnalysis")
public class ShapeFileAnalysisServiceImp  {

	@Autowired(required = false)
	private ShapeFileDataEditServer shapeFileAnalysis;

	public String analyseFile(Map<String, String[]> param, String filePath, String uid, String un) {
		try {
			// 解压文件
			String unZipFile = filePath.replace(".ZIP", "").replace(".zip", "");
			File dir = new File(unZipFile);
			if (!dir.isDirectory()) {
				dir.mkdirs();
			}
			ZipperUtils.upZipFile(new File(filePath), unZipFile);
			FilenameFilter filter = new FilenameFilter() {
				public boolean accept(File dir, String name) {
					return name.endsWith(".shp") || name.endsWith(".SHP");
				}
			};
			String[] children = dir.list(filter);
			if (children == null || children.length <= 0) {
				return null;
			}
			String shapeFile = unZipFile + "/" + children[0];
			
			// 解释文件
			List<SimpleFeature> graphic = shapeFileAnalysis.queryFeature(shapeFile, null);
			HashMap<String, Object> result = new HashMap<String, Object>();
			result.put("status", true);
			result.put("graphic", AnalyseUtil.getGemetry(graphic));
			return JsonUtils.toJSONString(result);
		} catch (Exception e) {
			e.printStackTrace();
			return "{\"status\":false}";
		}
	}
}
